package com.nuc.iblog.controler;

import com.nuc.iblog.MyWebAppConfigurer;
import com.nuc.iblog.entity.User;
import com.nuc.iblog.entity.UserBlog;
import com.nuc.iblog.service.UserBlogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RequestMapping("cl")
@Controller
public class ClUserBlogController {
    Logger log = LoggerFactory.getLogger(ClUserBlogController.class);
    @Autowired
    UserBlogService userBlogService;
    @ResponseBody
    @RequestMapping("/modifyUserBlog")
    public UserBlog modify(@RequestParam(name = "blogpic",required = false)MultipartFile multipartFile,@RequestParam("musicshow")int musicshow, @RequestParam("musiclist")int musiclist, @RequestParam("gallery")int gallery, @RequestParam("link")String link, @RequestParam("articlenum")int articlenum, HttpSession httpSession){
        //上传博客头图
        User user=(User)httpSession.getAttribute("User");
        UserBlog userBlog=userBlogService.findByuser(user);
        if(multipartFile!=null){
            String picname=createfilename(multipartFile);
            String picurl= MyWebAppConfigurer.Pathpic()+picname;
            String picurll="blogFile/"+picname;
            File blogpic=new File(picurl);
            userBlog.setBlogpicurl(picurll);
            try {
                multipartFile.transferTo(blogpic);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        userBlog.setMusiclist(musiclist);
        userBlog.setMusicshow(musicshow);
        userBlog.setArticlenum(articlenum);
        userBlog.setGallery(gallery);
        userBlog.setLink(link);
        userBlogService.ModifyBlog(userBlog);
        return userBlog;
    }

    public void savepic(MultipartFile multipartFile, File file){
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String createfilename(MultipartFile file){
        String filename = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newfilename = UUID.randomUUID() + filename;
        String replace = newfilename.replace("-", "");
        return replace;
    }
}
